package com.wq;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.List;

public class StockApplication {


    public static void main(String[] args) {
        List<User> users = new ArrayList<User>();
        users.add(new User("wang", 24));
        users.add(new User("chen", 26));
        users.add(new User("sun", 24));
        //保留age不为26的User
        Predicate<User> predicate1 = new Predicate<User>() {
            public boolean apply(User user) {
                if (user.getAge() != 26) {
                    return true;
                }
                return false;
            }
        };
        //保留userName 是 chen 的user
        Predicate<User> predicate2 = new Predicate<User>() {
            public boolean apply(User user) {
                return StockApplication.equals(user.getUserName(), "chen");
            }
        };
        //保留age不为 26 [且] userName 是 chen的User
        Predicate<User> predicate1_and_predicate2 = Predicates.and(predicate1, predicate2);
        //保留age不为26 [或] userName 是 chen的User
        Predicate<User> predicate1_or_predicate2 = Predicates.or(predicate1, predicate2);
        //与predicate1条件相反:只保留age为26的User
        Predicate<User> notpredicate1 = Predicates.not(predicate1);

        List<User> filteredUsers1 = Lists.newArrayList(Iterables.filter(users, predicate1));
        List<User> filteredUsers2 = Lists.newArrayList(Iterables.filter(users, predicate2));
        List<User> filteredUsers1and2 = Lists.newArrayList(Iterables.filter(users, predicate1_and_predicate2));
        List<User> filteredUsers1or2 = Lists.newArrayList(Iterables.filter(users, predicate1_or_predicate2));
        List<User> filteredUsersNot1 = Lists.newArrayList(Iterables.filter(users, notpredicate1));
        System.out.println("filteredUsers1: " + filteredUsers1.size());          //2->  wang sun
        System.out.println("filteredUsers2:  " + filteredUsers2.size());         //1-> chen
        System.out.println("filteredUsers1and2:  " + filteredUsers1and2.size()); //0->
        System.out.println("filteredUsers1or2:  " + filteredUsers1or2.size());   //3-> wang chang sun
        System.out.println("filteredUsersNot1:  " + filteredUsersNot1.size());   //1-> chen
    }

    public static boolean equals(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));
    }
}

class User {
    private String userName;
    private int age;

    public User(String userName, int age) {
        this.userName = userName;
        this.age = age;
    }

    public String getUserName() {
        return userName;
    }

    public int getAge() {
        return age;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
